package cn.zyjblogs.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {
    public static void main(String[] args) {

        //线程池机制

        //思路
        //1. 创建一个线程池
        //2. 如果有客户端链接，就创建一个线程与之通讯
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();

        //创建ServerSocket
        try {
            ServerSocket serverSocket = new ServerSocket(6666);
            System.out.println("服务器启动了");
            while (true) {
                System.out.println("等待连接");
                final Socket socket = serverSocket.accept();
                System.out.println("连接到一个客户端了");
                //就创建一个线程与之通讯
                newCachedThreadPool.execute(() -> {
                    //可以和客户端通讯
                    handler(socket);
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void handler(Socket socket) {
        try (InputStream inputStream = socket.getInputStream()) {
            System.out.println("线程信息id = "+Thread.currentThread().getId()+"  名称 = "+Thread.currentThread().getId());
            byte[] bytes = new byte[1024];
            while (true) {
                System.out.println("read....");
                int read = inputStream.read(bytes);
                System.out.println("线程信息id = "+Thread.currentThread().getId()+"  名称 = "+Thread.currentThread().getId());
                if (read == -1) {
                    break;
                }
                //输出客户端发送的数据
                System.out.println(new String(bytes,0,read));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭客户端链接");
        }
    }
}
